#include "web/WebPageSearcher.hh"
#include "web/WebPageQuery.hh"
#include "SplitToolCppJieba.hh"
#include "Cache/SingnalRedis.hh"
#include "Configuration.hh"
#include "Cache/CacheManager.hh"
#include "Log/Log.hh"

#include <thread>

using std::this_thread::get_id;
WebPageSearcher::WebPageSearcher(string keys, const TcpConnectionPtr conn)
    : _sought(keys)
    , _conn(conn){

}
void WebPageSearcher::doQuery(){

    SplitToolCppJieba jieba;

    WebPageQuery query(&jieba);
    auto v = query.doQuery(_sought);

    vector<pair<int, vector<double>>> resultVec;
    bool ret = query.executeQuery(v, resultVec);
    if(ret == false){
        _conn->send(query.returnNoAnswer());
        return;
    }
    vector<int> result = query.CosSort(resultVec, v);
    
    string json = query.createJson(result, v);

    // // 存储到redis中
    // if(SingnalRedis::createRedis()->getRedis().set(string("200") + _sought, json) == false){
    //     cout << "redis set error" << endl;
    // }
    // cout << "redis set success" << endl;



    // 存储到Cache中
    thread::id p_id = get_id();

    auto pid_vec = CacheManager::createCacheManager()->getPidVec();
    size_t serial = 0;
    for(; serial < pid_vec.size(); ++serial){
        if(pid_vec[serial] == p_id){
            break;
        }
    }

    CacheManager::createCacheManager()->getCaches()[serial].addElement(string("200") + _sought, json);
    Log::info("%ld 号Cache存储成功, Key: %s", serial, string("200") + _sought.c_str());

    _conn->send(json);
}